package org.epidroid.epidroid.epirss;

import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import org.epidroid.epidroid.EpiDroid;
import org.epidroid.epidroid.R;
import org.epidroid.epidroid.epirss.PullToRefreshListView.OnRefreshListener;

import android.app.ListActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class RssView extends ListActivity {
	private String feedUrl = "http://feeds2.feedburner.com/epita";
	private int[] listviewRowId;
	private boolean reloadingData = false;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rss_articles);
		
		EpiDroid.rssDb = new RssDbAdaptater(this);
		EpiDroid.rssDb.open();
		
		/** Handle "reload" clicks. */
		//Button reloadBtn = (Button) findViewById(R.id.reload);
		//reloadBtn.setOnClickListener(reloadListener);
		
		((PullToRefreshListView) getListView()).setOnRefreshListener(new OnRefreshListener() {
		    @Override
		    public void onRefresh() {
		        // Do work to refresh the list here.
		    	reloadRss ();
		    }
		});

		/**
		 * By using setAdpater method in listview we an add string array in list.
		 */
		String[] defaultItems = { "Loading the articles..." };
		setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, defaultItems));

		/** Load data. */
		fillData();

		/* Reload automatically */
		try {
			SharedPreferences settings = getSharedPreferences("SettingsRSS", 0);
			String old_date = DateFormat.getDateTimeInstance().format((new GregorianCalendar(1970, 1, 1)).getTime());
			Date lastUpdate = DateFormat.getDateTimeInstance().parse(settings.getString("LastUpdate", old_date));

			Date reload_date = new Date();
			reload_date.setHours(reload_date.getHours() - 6);

			Log.i("EpiDroid", "Last refresh: " + settings.getString("LastUpdate", old_date));
			Log.i("EpiDroid", "Last refresh: " + lastUpdate.toString());
			Log.i("EpiDroid", "Force refresh if older than: " + reload_date.toString());

			if (lastUpdate.before(reload_date))
			{
				reloadRss();

				SharedPreferences.Editor editor = settings.edit();
				editor.putString("LastUpdate", DateFormat.getDateTimeInstance().format((new GregorianCalendar()).getTime()));
				editor.commit();

				Log.i("EpiDroid", "Rss resfheded");
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);

		Intent intent = new Intent(v.getContext(), RssArticleView.class);
		Bundle b = new Bundle();

		int rowId = listviewRowId[position - 1];
		b.putInt("articleId", rowId);
		intent.putExtras(b);

		startActivity(intent);
	}

	/**
	 * Fill the text with the articles
	 */
	public void fillData() {
		/**
		 * By using setAdpater method in listview we an add string array in list.
		 */
		Cursor c = EpiDroid.rssDb.fetchAllArticles();
		List<RssArticle> articles = new ArrayList<RssArticle>();
		listviewRowId = new int[c.getCount()];

		for (int i = 0; i < c.getCount(); i++) {
			String title = c.getString(c.getColumnIndex("title"));
			String published = c.getString(c.getColumnIndex("published"));
			articles.add(new RssArticle(title, "", "", "", published));
			listviewRowId[i] = Integer.parseInt(c.getString(c.getColumnIndex("id")));

			c.moveToNext();
		}
		c.close();

		RssListAdapter adapter = new RssListAdapter(this, R.layout.rss_articles_row, articles);
		setListAdapter(adapter);
	}

	/**
	 * Display a short notification to the user
	 */
	private void notify(String message) {
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
	}

	private void reloadRss() {
		if (!reloadingData)
		{
			reloadingData = true;
			new LoadRssTask().execute();
		}
	}

	/**
	 * Load the RSS feed and load the entries found in the database
	 */
	private class LoadRssTask extends AsyncTask<Void, Void, String> {
//		protected void onPreExecute() {
//			//ProgressBar reloadBar = (ProgressBar) findViewById(R.id.reloadBar);
//			//reloadBar.setVisibility(View.VISIBLE);
//
//			//Button reloadBtn = (Button) findViewById(R.id.reload);
//			//reloadBtn.setEnabled(false);
//		}

		protected void onPostExecute(String msg) {
			RssView.this.notify(msg);
			fillData();

			//ProgressBar reloadBar = (ProgressBar) findViewById(R.id.reloadBar);
			//reloadBar.setVisibility(View.INVISIBLE);

			//Button reloadBtn = (Button) findViewById(R.id.reload);
			//reloadBtn.setEnabled(true);
			((PullToRefreshListView) getListView()).onRefreshComplete();
			reloadingData = false;
		}

		protected String doInBackground(Void... params) {
			int newArticles = 0;
			LoadRss rss = new LoadRss(feedUrl);
			try {
				List<RssArticle> rssArticles = rss.LoadFeed();

				for (RssArticle article : rssArticles)
				{
					if (EpiDroid.rssDb.existsArticle(article))
						EpiDroid.rssDb.updateArticle(article);
					else {
						EpiDroid.rssDb.createArticle(article);
						newArticles++;
					}
				}

				if (newArticles == 0)
					return (getString(R.string.rss_no_news));
				else if (newArticles == 1)
					return (getString(R.string.rss_new));
				else
					return (Integer.toString(newArticles) + getString(R.string.rss_news));
			} catch (Exception e) {
				return (e.toString());
			}
		}
	}
}